<template>
  <div class="form-page">
    <Card :bordered="false" :dis-hover="true">
      <p slot="title" style="color: #666">
        <span
          class="iconfont icon-changyongtubiao-xianxingdaochu-zhuanqu-"
          style="font-size: 20px"
        ></span>
        添加模式
      </p>
      <p slot="extra" style="color: #999; font-size: 12px">
        <label style="color: #ff3b30">*</label> 为必填
      </p>
      <Form
        ref="formValidate"
        :model="bloc.model"
        :rules="ruleValidate"
        :label-width="100"
      >
        <FormItem
          label="设备分类："
          prop="sortId"
          style="display: none"
          required
        >
          <Select
            v-model="bloc.model.sortId"
            @on-change="handleChange(bloc.model.sortId)"
            disabled
          >
            <Option
              v-for="item in bloc.sortList"
              :value="item.id"
              :key="item.sortName"
              >{{ item.sortName }}
            </Option>
          </Select>
        </FormItem>

        <FormItem
          label="设备型号："
          prop="modelId"
          style="display: none"
          required
        >
          <Select v-model="bloc.model.modelId" disabled>
            <Option
              v-for="item in bloc.modelList"
              :value="item.id"
              :key="item.id"
              >{{ item.modelName }}
            </Option>
          </Select>
        </FormItem>
        <FormItem label="运动分类：" prop="classification" required>
          <el-select v-model="bloc.model.classification" style="width: 400px">
            <el-option
              v-for="item in cateList"
              :value="item.value"
              :key="item.value"
              >{{ item.label }}
            </el-option>
          </el-select>
        </FormItem>
        <FormItem label="模式名称：" prop="modeName" required>
          <Input v-model="bloc.model.modeName" style="width: 400px" />
        </FormItem>
        <FormItem label="模式英文名称：" prop="modeNameEn" required>
          <Input v-model="bloc.model.modeNameEn" style="width: 400px" />
        </FormItem>
        <FormItem label="模式图标：" prop="iconUrl" required>
          <div
            class="demo-upload-list"
            v-for="(item, index) in fileList"
            :key="index"
          >
            <template v-if="item.status === 'finished'">
              <img :src="item.iconUrl" />
              <div class="demo-upload-list-cover">
                <Icon
                  type="ios-eye-outline"
                  @click.native="handleView(item.iconUrl)"
                ></Icon>
                <Icon
                  type="ios-trash-outline"
                  @click.native="handleRemove(item)"
                ></Icon>
              </div>
            </template>
            <template v-else>
              <Progress
                v-if="item.showProgress"
                :percent="item.percentage"
                hide-info
              ></Progress>
            </template>
          </div>
          <Upload
            :action="uploadActionImg"
            :show-upload-list="false"
            :max-size="50"
            :format="['JPG', 'PNG']"
            :headers="uploadHeaders"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            :on-success="handleSuccess"
            type="drag"
            multiple
            style="display: inline-block; width: 58px; margin-left: 15px"
          >
            <div style="width: 58px; height: 58px; line-height: 58px">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
            <Modal title="View Image" v-model="visible">
              <img :src="imgUrl" v-if="visible" style="width: 100%" />
            </Modal>
          </Upload>
          <p style="margin-left: 15px">支持 JPG、PNG 格式，图片小于50k</p>
        </FormItem>

        <FormItem label="选中模式图标：" prop="selectedIconUrl" required>
          <div
            class="demo-upload-list"
            v-for="(item, index) in fileListSelectIcon"
            :key="index"
          >
            <template v-if="item.status === 'finished'">
              <img :src="item.selectedIconUrl" />
              <div class="demo-upload-list-cover">
                <Icon
                  type="ios-eye-outline"
                  @click.native="handleView(item.selectedIconUrl)"
                ></Icon>
                <Icon
                  type="ios-trash-outline"
                  @click.native="handleRemoveSelectIcon(item)"
                ></Icon>
              </div>
            </template>
            <template v-else>
              <Progress
                v-if="item.showProgress"
                :percent="item.percentage"
                hide-info
              ></Progress>
            </template>
          </div>
          <Upload
            :action="uploadActionImg"
            :show-upload-list="false"
            :max-size="50"
            :format="['JPG', 'PNG']"
            :headers="uploadHeaders"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            :on-success="handleSuccessSelectIcon"
            type="drag"
            multiple
            style="display: inline-block; width: 58px; margin-left: 15px"
          >
            <div style="width: 58px; height: 58px; line-height: 58px">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
            <Modal title="View Image" v-model="visible">
              <img :src="imgUrl" v-if="visible" style="width: 100%" />
            </Modal>
          </Upload>
          <p style="margin-left: 15px">支持 JPG、PNG 格式，图片小于50k</p>
        </FormItem>

        <FormItem label="模式背景：" prop="backgroundUrl" required>
          <div
            class="demo-upload-list"
            v-for="(item, index) in fileListBackground"
            :key="index"
          >
            <template v-if="item.status === 'finished'">
              <img :src="item.backgroundUrl" />
              <div class="demo-upload-list-cover">
                <Icon
                  type="ios-eye-outline"
                  @click.native="handleView(item.backgroundUrl)"
                ></Icon>
                <Icon
                  type="ios-trash-outline"
                  @click.native="handleRemoveBackground(item)"
                ></Icon>
              </div>
            </template>
            <template v-else>
              <Progress
                v-if="item.showProgress"
                :percent="item.percentage"
                hide-info
              ></Progress>
            </template>
          </div>
          <Upload
            :action="uploadActionImg"
            :show-upload-list="false"
            :max-size="50"
            :format="['JPG', 'PNG']"
            :headers="uploadHeaders"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            :on-success="handleSuccessBackground"
            type="drag"
            multiple
            style="display: inline-block; width: 58px; margin-left: 15px"
          >
            <div style="width: 58px; height: 58px; line-height: 58px">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
            <Modal title="View Image" v-model="visible">
              <img :src="imgUrl" v-if="visible" style="width: 100%" />
            </Modal>
          </Upload>
          <p style="margin-left: 15px">支持 JPG、PNG 格式，图片小于50k</p>
        </FormItem>
        <FormItem label="app图标：" prop="appUrl" required>
          <div
            class="demo-upload-list"
            v-for="(item, index) in appList"
            :key="index"
          >
            <template v-if="item.status === 'finished'">
              <img :src="item.appUrl" />
              <div class="demo-upload-list-cover">
                <Icon
                  type="ios-eye-outline"
                  @click.native="handleView(item.appUrl)"
                ></Icon>
                <Icon
                  type="ios-trash-outline"
                  @click.native="handleRemoveApp(item)"
                ></Icon>
              </div>
            </template>
            <template v-else>
              <Progress
                v-if="item.showProgress"
                :percent="item.percentage"
                hide-info
              ></Progress>
            </template>
          </div>
          <Upload
            :action="uploadActionImg"
            :show-upload-list="false"
            :max-size="200"
            :format="['JPG', 'PNG']"
            :headers="uploadHeaders"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            :on-success="handleSuccessApp"
            type="drag"
            multiple
            style="display: inline-block; width: 58px; margin-left: 15px"
          >
            <div style="width: 58px; height: 58px; line-height: 58px">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
            <Modal title="View Image" v-model="visible">
              <img :src="imgUrl" v-if="visible" style="width: 100%" />
            </Modal>
          </Upload>
          <p style="margin-left: 15px">支持 JPG、PNG 格式，图片小于200k</p>
        </FormItem>

        <FormItem label="模式编号：" prop="sn" required>
          <Input v-model="bloc.model.sn" style="width: 400px" />
          <!--          <Select v-model="bloc.model.sn">-->
          <!--            <Option-->
          <!--              v-for="item in snList"-->
          <!--              :value="item"-->
          <!--              :key="item"-->
          <!--            >{{ item}}-->
          <!--            </Option>-->
          <!--          </Select>-->
        </FormItem>

        <!--        <FormItem label="模式版本：" prop="versions">-->
        <!--          <Input v-model="bloc.model.versions"/>-->
        <!--        </FormItem>-->

        <FormItem label="模式文件：" prop="url" required>
          <Upload
            :show-upload-list="false"
            :action="uploadAction"
            :max-size="2"
            :format="['bin']"
            :headers="uploadHeaders"
            :on-format-error="handleFormatError1"
            :on-exceeded-size="handleMaxSize1"
            :on-success="handleSuccessFile"
          >
            <Button icon="ios-filing">选择附件</Button>
          </Upload>
          <a v-if="bloc.model.extName" :href="bloc.model.url">{{
            bloc.model.extName
          }}</a>
          <p style="margin-left: 15px">支持 bin 格式，小于2K</p>
        </FormItem>
        <FormItem label="模式状态：" required>
          <i-switch @on-change="switchStatus" v-model="enable"></i-switch>
        </FormItem>
        <FormItem label="模式简介：" prop="describe" required>
          <Input
            style="width: 400px"
            type="textarea"
            v-model="bloc.model.describe"
            :rows="5"
            maxlength="5000"
            show-word-limit
          ></Input>
        </FormItem>
        <FormItem label="模式简介(英文)：" prop="describeEn" required>
          <Input
            style="width: 400px"
            type="textarea"
            v-model="bloc.model.describeEn"
            :rows="5"
            maxlength="5000"
            show-word-limit
          ></Input>
        </FormItem>
        <FormItem label="模式详情:" prop="text" required>
          <HtmlEditor
            id="ueditor"
            :config="config"
            :content="bloc.initContent"
            :useCustomUpload="true"
            @change="ueditorChange"
            style="width: 100%; max-width: 1000px; overflow: auto"
          ></HtmlEditor>
        </FormItem>
      </Form>
      <div style="margin: 20px 0px 35px 25px">
        <Button style="width: 100px; height: 40px" @click="handleCancel()"
          >返回</Button
        >
        <Button
          style="margin-left: 30px; width: 100px; height: 40px"
          type="primary"
          :loading="btnload.loading"
          @click="handleSubmit('formValidate')"
          >保存
        </Button>
      </div>
    </Card>
  </div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator";
import { AutomaticBloc } from "./AutomaticBloc";
import { store } from "@/store/Store";
import { baseUrl } from "@/base/Request";
import { Loading } from "@/base/Loading";
import { router } from "@/config/Router";
import HtmlEditor from "@/component/HtmlEditor.vue";

@Component({
  components: { HtmlEditor },
})
export default class extends Vue {
  @Prop({ type: Number })
  readonly init!: number;
  bloc = new AutomaticBloc();
  btnload = new Loading();
  snList: any = {
    1: "GY",
    2: "SQ",
    3: "SY",
    4: "ZW",
    5: "WZ",
    6: "ORDER",
  };
  cateList = [
    {
      value: "球类运动",
      label: "球类运动",
    },
    {
      value: "骑行运动",
      label: "骑行运动",
    },
    {
      value: "田径运动",
      label: "田径运动",
    },
    {
      value: "山地运动",
      label: "山地运动",
    },
    {
      value: "水上运动",
      label: "水上运动",
    },
    {
      value: "武术运动",
      label: "武术运动",
    },
    {
      value: "体操运动",
      label: "体操运动",
    },
    {
      value: "冰上运动",
      label: "冰上运动",
    },
    {
      value: "器械运动",
      label: "器械运动",
    },
    {
      value: "竞技运动",
      label: "竞技运动",
    },
    {
      value: "舞蹈运动",
      label: "舞蹈运动",
    },
    {
      value: "瑜伽运动",
      label: "瑜伽运动",
    },
    {
      value: "体脂程序",
      label: "体脂程序",
    },
    {
      value: "院士推荐",
      label: "院士推荐",
    },
  ];
  config = {
    imageUrl: this.uploadActionImg, // 图片上传提交地址
    imagePath: "",
    imageToken: store.state.auth.accessToken,
    imageFieldName: "file",
  };
  formValidate: any = {
    type: "",
    switch: true,
  };
  ruleValidate: any = {
    describe: [
      { required: true, message: "模式简介不能为空", trigger: "blur" },
    ],
    describeEn: [
      { required: true, message: "模式英文简介不能为空", trigger: "blur" },
    ],
    cateName: [
      { required: true, message: "运动分类不能为空", trigger: "blur" },
    ],
    text: [{ required: true, message: "模式详情不能为空", trigger: "blur" }],
    iconUrl: [{ required: true, message: "模式图片不能为空", trigger: "blur" }],
    backgroundUrl: [
      { required: true, message: "模式背景图不能为空", trigger: "blur" },
    ],
    appUrl: [{ required: true, message: "app背景图不能为空", trigger: "blur" }],
    selectedIconUrl: [
      { required: true, message: "选中模式图片不能为空", trigger: "blur" },
    ],
    modeName: [
      { required: true, message: "模式名称不能为空", trigger: "blur" },
    ],
    modeNameEn: [
      { required: true, message: "模式英文名称不能为空", trigger: "blur" },
    ],
    modelId: [
      {
        required: true,
        message: "设备型号不能为空",
        trigger: "change",
        type: "number",
      },
    ],
    sn: [{ required: true, message: "模式编号不能为空", trigger: "blur" }],
    sortId: [
      {
        required: true,
        message: "设备分类不能为空",
        trigger: "change",
        type: "number",
      },
    ],
    url: [{ required: true, message: "模式文件不能为空", trigger: "blur" }],
    versions: [
      { required: true, message: "模式版本不能为空", trigger: "blur" },
    ],
  };
  $refs!: {
    formValidate: HTMLFormElement;
  };
  enable = true;

  switchStatus(status) {
    if (status) {
      this.bloc.model.issueStatus = "ISSUE";
    } else {
      this.bloc.model.issueStatus = "NOT_ISSUE";
    }
  }

  get uploadHeaders() {
    return {
      Authorization: "Bearer " + store.state.auth.accessToken,
    };
  }

  get uploadAction() {
    return `${baseUrl}/api/upload/packet`;
  }

  get uploadActionImg() {
    return `${baseUrl}/api/upload/image`;
  }

  imgUrl = "";
  visible = false;

  get fileList() {
    return this.bloc.fileList.map((x) => {
      return { name: "name", iconUrl: x, status: "finished" };
    });
  }
  get fileListSelectIcon() {
    return this.bloc.fileSelectIcon.map((x) => {
      return { name: "name", selectedIconUrl: x, status: "finished" };
    });
  }
  get fileListBackground() {
    return this.bloc.fileListBackground.map((x) => {
      return { name: "name", backgroundUrl: x, status: "finished" };
    });
  }
  get appList() {
    return this.bloc.appList.map((x) => {
      return { name: "name", appUrl: x, status: "finished" };
    });
  }
  handleView(url) {
    this.imgUrl = url;
    this.visible = true;
  }

  handleRemove(file) {
    this.bloc.fileList.splice(this.bloc.fileList.indexOf(file), 1);
  }
  handleRemoveSelectIcon(file) {
    this.bloc.fileSelectIcon.splice(this.bloc.fileSelectIcon.indexOf(file), 1);
  }
  handleRemoveBackground(file) {
    this.bloc.fileListBackground.splice(
      this.bloc.fileListBackground.indexOf(file),
      1
    );
  }
  handleRemoveApp(file) {
    this.bloc.appList.splice(this.bloc.appList.indexOf(file), 1);
  }
  handleFormatError(file) {
    this.$Message.error("请选择格式为.JPG、.PNG格式的文件");
  }

  handleMaxSize(file) {
    this.$Message.error("文件不能超出50k");
  }

  handleFormatError1(file) {
    this.$Message.error("请选择格式为.bin格式的文件");
  }

  handleMaxSize1(file) {
    this.$Message.error("文件不能超出2K");
  }

  handleChange(sortId) {
    this.bloc
      .getAllModel(
        this.bloc.page.pageIndex,
        this.bloc.page.pageSize,
        sortId,
        "ASC",
        undefined
      )
      .then((res) => {})
      .finally(() => {
        this.bloc.getAllSort(
          this.bloc.page.pageIndex,
          this.bloc.page.pageSize,
          "ASC"
        );
      });
  }

  handleSuccess(res, file) {
    this.bloc.model.iconUrl = res.data[0];
    if (this.bloc.fileList.length > 0) {
      this.bloc.fileList = [];
    }
    this.bloc.fileList.push(this.bloc.model.iconUrl);
  }
  handleSuccessSelectIcon(res, file) {
    this.bloc.model.selectedIconUrl = res.data[0];
    if (this.bloc.fileSelectIcon.length > 0) {
      this.bloc.fileSelectIcon = [];
    }
    this.bloc.fileSelectIcon.push(this.bloc.model.selectedIconUrl);
  }
  handleSuccessBackground(res, file) {
    this.bloc.model.backgroundUrl = res.data[0];
    if (this.bloc.fileListBackground.length > 0) {
      this.bloc.fileListBackground = [];
    }
    this.bloc.fileListBackground.push(this.bloc.model.backgroundUrl);
  }
  handleSuccessApp(res, file) {
    this.bloc.model.appUrl = res.data[0];
    if (this.bloc.appList.length > 0) {
      this.bloc.appList = [];
    }
    this.bloc.appList.push(this.bloc.model.appUrl);
  }
  handleSuccessFile(res, file) {
    this.bloc.model.url = res.data.url;
    this.bloc.model.extName = file.name;
  }

  handleSubmit(name) {
    this.$refs[name].validate((valid) => {
      if (valid) {
        this.btnload.loading = true;
        
        this.bloc
          .addSeftMotion(
            this.bloc.model.describe,
            this.bloc.model.iconUrl,
            this.bloc.model.selectedIconUrl,
            this.bloc.model.backgroundUrl,
            this.bloc.model.appUrl,
            this.bloc.model.modeName,
            this.bloc.model.modeNameEn,
            this.bloc.model.sn,
            this.bloc.model.modelId,
            this.bloc.model.sortId,
            this.bloc.model.url,
            this.bloc.model.issueStatus,
            this.bloc.model.classification,
            this.bloc.model.describeEn,
          )
          .then((res) => {
            this.$Message.success("保存成功");
            this.$router.push({
              path: "/device/nav/automatic/" + this.$route.query.id,
              query: { sortId: this.$route.query.sortId },
            });
            if (res.message !== "") {
              this.$Message.error(res.message);
            }
          })
          .catch((err) => {
            this.$Message.error(err.message);
            // this.$Message.error("保存失败");
          })
          .finally(() => {
            this.btnload.loading = false;
          });
      }
    });
    console.log(this.bloc.model, "-----------hdajshdai");
  }
  ueditorChange(ue) {
    this.bloc.model.text = ue.getContent();
  }
  handleCancel() {
    this.$router.push({
      path: "/device/nav/automatic/" + this.$route.query.id,
      query: { sortId: this.$route.query.sortId },
    });
  }

  mounted() {
    this.bloc.model.issueStatus = "ISSUE";
    this.bloc.getAllSort(
      this.bloc.page.pageIndex,
      this.bloc.page.pageSize,
      "ASC"
    );

    this.bloc.getModel(Number(this.$route.query.id)).then((res) => {
      this.bloc.model.sortId = res.data.sortId;
      this.bloc.model.modelId = res.data.id;
      this.bloc.modelList = [
        { id: res.data.id, modelName: res.data.modelName },
      ];
    });
  }
}
</script>
<style lang="less" scoped>
.top {
  height: 50px;
  width: 100%;
  border-bottom: 1px solid rgba(204, 204, 204, 1);
  font-size: 18px;
  line-height: 50px;
}

/deep/ .ivu-form-item-content {
  display: flex !important;
  justify-content: start !important;
  align-items: center !important;
}
</style>
